package edu.mtu.citizenscience.ethnography.util;

import edu.mtu.citizenscience.ethnography.R;
import edu.mtu.citizenscience.ethnography.RegisterActivity;
import edu.mtu.citizenscience.ethnography.uploader.EthnographyUploadService;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.widget.EditText;

public class LoginDialogFragment extends DialogFragment {
	private static final String LOG_TAG = "LoginDialogFragment";
	public static final String FRAG_TAG = LOG_TAG;

	private FragmentActivity callingActivity;
	
	public void setCallingActivity(FragmentActivity activity) {
		this.callingActivity = activity;
	}
	
	private EditText usernameField;
	private EditText passwordField;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		LayoutInflater inflater = getActivity().getLayoutInflater();

		builder.setView(inflater.inflate(R.layout.dialog_login, null)).
		setPositiveButton(R.string.login_ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub, remove debug code
				String username = usernameField.getText().toString();
				String password = passwordField.getText().toString();
				
				Intent intent = new Intent(callingActivity, EthnographyUploadService.class);
				intent.putExtra(EthnographyUploadService.INPUT_METHOD, EthnographyUploadService.METHOD_LOGIN);
				intent.putExtra(EthnographyUploadService.INPUT_USERNAME, username);
				intent.putExtra(EthnographyUploadService.INPUT_PASSWORD, password);
				
				callingActivity.startService(intent);
			}
		})
		.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				LoginDialogFragment.this.getDialog().cancel();
			}
		}).setNeutralButton(R.string.register, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String username = usernameField.getText().toString();
				String password = passwordField.getText().toString();
				
				Intent intent = new Intent(callingActivity, RegisterActivity.class);
				intent.putExtra(EthnographyUploadService.INPUT_USERNAME, username);
				intent.putExtra(EthnographyUploadService.INPUT_PASSWORD, password);
				
				startActivity(intent);
			}
		});

		Dialog dialog = builder.show();
		
		usernameField = (EditText) dialog.findViewById(R.id.username);
		passwordField = (EditText) dialog.findViewById(R.id.password);
		return dialog;
	}
	
}
